package com.zhuzg;

import com.digitalpetri.modbus.master.ModbusTcpMaster;
import com.digitalpetri.modbus.master.ModbusTcpMasterConfig;
import com.digitalpetri.modbus.requests.ReadHoldingRegistersRequest;
import com.digitalpetri.modbus.responses.ModbusResponse;
import com.digitalpetri.modbus.responses.ReadHoldingRegistersResponse;
import io.netty.buffer.ByteBuf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@SpringBootApplication
public class ModBusDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        System.out.println("hi............");
        SpringApplication.run(ModBusDemo.class,args);
/*
        // 仅仅是配置
        ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("127.0.0.1")
                .setPort(502)
                .setTimeout(Duration.ofSeconds(20))
                .build();

        // 创建连接
        ModbusTcpMaster master = new ModbusTcpMaster(config);

       *//* for (int i = 0; i < 9; i++) {
            CompletableFuture<ReadHoldingRegistersResponse> future =
                    master.sendRequest(new ReadHoldingRegistersRequest(i, 1), 1);
            ReadHoldingRegistersResponse response = future.get();
            ByteBuf byteBuf = response.getRegisters();
            short aShort = byteBuf.readShort();
            System.out.println("读取到的结果是 ：" + aShort  );
        }*//*

        // 读取湿度
        CompletableFuture<ReadHoldingRegistersResponse> future =
                master.sendRequest(new ReadHoldingRegistersRequest(0, 1), 1);
        ReadHoldingRegistersResponse response = future.get();
        ByteBuf byteBuf = response.getRegisters();
        short aShort = byteBuf.readShort();
        System.out.println("湿度是 ： " + aShort/10f);

        // 读取温度
        future =
                master.sendRequest(new ReadHoldingRegistersRequest(1, 1), 1);
         response = future.get();
         byteBuf = response.getRegisters();
        int aShort1 = byteBuf.readUnsignedShort();
        System.out.println("温度是 ： " + (aShort1-65536)/10f);


        // 读取光照
        future =
                master.sendRequest(new ReadHoldingRegistersRequest(2, 2), 1);
        response = future.get();
        byteBuf = response.getRegisters();
        int sun = byteBuf.readInt();
        System.out.println("光照 ： " + sun/1000f);*/











    }
}
